[참조]
간단한 프로그램은 함수만으로 효율적인 절차지향(procedure-oriented) 프로그래밍을 작성할 수 있다.
하지만 프로그램이 커지면 객체의 틀(뼈대)인 클래스(class)를 사용한 객체지향(object-oriented) 프로그래밍이 필요하다.
(예시)
내가 생각하는 월드 "클래스" 보디빌더 "객체"들은 "이승철", "황철순" 등이 있다.
방법 1)
(예시)
class Simple: # 클래스 Simple 정의
pass
# 객체 생성 후 멤버 변수 추가
a = Simple() # 클래스 Simple의 객체 a 생성
a.name = 'Jane' # 객체 a의 멤버변수 name 추가
a.phone = '123-456' # 객체 a의 멤버변수 phone 추가
방법 1)
(예시)
class Account:
numOfAccount = 0 # 클래스 변수
def __init__(self, name): # 생성자 함수 정의
self.name = name # 객체 변수 name
self.balances = 0 # 객체 변수 balances
Account.numOfAccount += 1
def withdraw(self, value): # withdraw 함수 정의
self.balances -= value
return self.balances
def deposit(self, value): # deposit 함수 정의
self.balances += value
return self.balances
def __del__(self): # 소멸자 함수 정의
Account.numOfAccount -= 1
a1 = Account('John') # 클래스 Account의 객체 a1 생성
# 객체 a1의 변수 name에 John을 할당
a1.deposit(10) # 객체 a1의 함수 deposit를 사용하여 10을 적립: balances = 0 + 10 = 10
a1.withdraw(2) # 객체 a1의 함수 withdraw를 사용하여 2을 인출: balances = 10 - 2 = 8
print(a1.balances) # 출력: 8
a2 = Account('Jane') # 클래스 Account의 객체 a2 생성
# 객체 a1의 변수 name에 Jane을 할당
print('no of Account:', Account.numOfAccount) # 출력: 2
함수에 self 인자가 없는 경우는 C의 static member와 동일하다.
(예시)
class Account:
numOfAccount = 0
@staticmethod
def makeZero(number):
Account.numOfAccount = number
(예시)
class Element: # 부모 클래스 Element의 선언
def __init__(self, id): # 생성자 함수
self.id = id
self.nodeIds = []
def computeStiffness(self): # 함수 생성
print('Element::computeStiffness')
def printElement(self): # 함수 생성
print(f'id : {self.id}')
class Q4Element(Element): # 부모 클래스 Element를 상속한 자녀 클래스 Q4Element의 선언
def __init__(self, id, nodeIds): # 생성자 함수
super().__init__(id) # 부모 클래스 생성자 호출
self.nodeIds = nodeIds
def computeStiffness(self):
print('Q4Element::computeStiffness')
# 자녀 클래스에서 부모 클래스의 생성자인 __init__()를 호출하는 방법은 다음 두 가지가 있다.
# 방법 1) super().__init__(id) 등과 같이 self를 사용하는 방법
# 방법 2) Element.__init__(self,id)와 같이 클래스 이름을 사용하고 함수에 self를 사용하는 방법
e = Q4Element(1, [1, 2, 3])
e.printElement() # 출력: id : 1
e.computeStiffness() # 출력: Q4Element::computeStiffness
(예시 1)
class Rectangle:
def __init__(self, *args, **kwargs):
if len(args) == 2:
self.w, self.h = args
elif 'width' in kwargs and 'height' in kwargs:
self.w = kwargs['width']
self.h = kwargs['height']
else:
self.w = self.h = 0
(예시 2)
class Rectangle:
def __init__(self):
self.w = None
self.h = None
@staticmethod
def fromWidthHeight(w, h):
r = Rectangle()
r.w = w
r.h = h
return r
@staticmethod
def fromArea(w, area):
r = Rectangle()
r.w = w
r.h = area / w
return r
r1 = Rectangle.fromWidthHeight(4, 10)
r2 = Rectangle.fromArea(4, 10)